//
//  HMChooseView.swift
//  HMWeiBo
//
//  Created by Apple on 16/8/7.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit

// 回顾一下代理. cell我也习惯代理 --  cell有可能有多个回调

protocol HMChooseViewCellDelegate: NSObjectProtocol {
    
    func didDelete(index: NSIndexPath)
    
}

private let HMChooseViewReuseIdentifier = "HMChooseViewReuseIdentifier"

private let HMChooseViewMargin:CGFloat = 10
private let HMChooseViewItemMargin: CGFloat = 5
private let HMChooseViewItemWH = (kUIScreenWidth - 2 * HMChooseViewItemMargin - 2 * HMChooseViewMargin) / 3

class HMChooseView: UICollectionView {

    // 闭包属性
    var closure: (()->())?
    
    // 创建一个数据源
    private lazy var images: [UIImage] = [UIImage]()
    
    var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    // 第一步: 重写父类的构造函数
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 第二步: 定义一个添加子类和设置子类控件约束的方法
    private func setupUI(){
        
        dataSource = self
        
        // 设置delegate方法
        delegate = self
        
        // 注册一个cell
        registerClass(HMChooseViewCell.self, forCellWithReuseIdentifier: HMChooseViewReuseIdentifier)
        
        // 属性
        flowLayout.itemSize = CGSizeMake(HMChooseViewItemWH, HMChooseViewItemWH)
        flowLayout.minimumInteritemSpacing = HMChooseViewItemMargin
        flowLayout.minimumLineSpacing = HMChooseViewItemMargin
    }
    
    // 对外公开一个方法,来实现数据源的添加
    // 把属性设置为私有的,防止外界 对这个属性 误操作
    
    func addImages(image: UIImage){
        
        images.append(image)
        // 当数据源发生改变的时候要刷新UI
        reloadData()
    }
    
    func getImages() -> [UIImage] {
        
        return images
    }
    
    //第三步: 懒加载控件
    //MARK:-- 懒加载控件

    
    deinit{
        
        print("chooseView 88")
    }
}

extension HMChooseView: UICollectionViewDataSource,HMChooseViewCellDelegate,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if images.count > 0 && images.count < 9 {
            return images.count + 1
        }
        return images.count
    }
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HMChooseViewReuseIdentifier, forIndexPath: indexPath) as! HMChooseViewCell
        
        // 数组越界了,我们防止越界
        if indexPath.item >= images.count {
            // 当 所有的 item 大于或者等于 数组的和的时候,会出现越界
            // 出现越界,就不能从数组里度值
            
            cell.image = UIImage(named: "compose_pic_add_highlighted")
            // 隐藏删除按钮
            cell.deleteButton.hidden = true
            
        } else {
            cell.image = images[indexPath.item]
            
            cell.deleteButton.hidden = false
        }
       // 随机颜色
        cell.backgroundColor = RandomColor()
        
        cell.index = indexPath
        
        // 设置代理
        cell.delegate = self
        
        return cell
        
    }
    
    func didDelete(index: NSIndexPath) {
    
        // 删除指定的数据
        images.removeAtIndex(index.item)
        
        // 数据源发生改变的时候,刷新UI
        reloadData()
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        // 选中的方法
        if indexPath.item >= images.count {
            
            // 跳转
            closure?()
        }
        
    }
}

// 一个Swift里 声明 多个类

class HMChooseViewCell: UICollectionViewCell {
    
    // 属性
    var image: UIImage?{
    
        didSet{
            
            iconImageView.image = image
            
        }
        
    }
    
    // 声明代理属性
    weak var delegate: HMChooseViewCellDelegate?
    
    //
    var index: NSIndexPath?
    
    // 第一步: 重写父类的构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 第二步: 定义一个添加子类和设置子类控件约束的方法
    private func setupUI(){
        
        contentView.addSubview(iconImageView)
        contentView.addSubview(deleteButton)
        
        // 设置约束
        iconImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
    }
    
    @objc private func deleteButtonClick(button: UIButton){
        
        if let indexPath = index {
            
            
            delegate?.didDelete(indexPath)
        }
        
        
    }
    
    //第三步: 懒加载控件
    //MARK:-- 懒加载控件
    private lazy var iconImageView: UIImageView = UIImageView()
    
    // 懒加载一个按钮
    private lazy var deleteButton: UIButton = {
    
        let button = UIButton(type: UIButtonType.Custom)
        
        // 属性
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        button.sizeToFit()
    
        button.addTarget(self, action: "deleteButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
        
    }()
}
